const Application = require("egg").Application
let path = require("path")
let Ioredis = require("ioredis")

let queryIp = require("./queryInTB")
let baseDir = path.resolve("./")
let helper = require("../app/extend/helper")

// 延时
const app = new Application({
	framework: path.join(baseDir, "./node_modules/egg"),
	baseDir: baseDir,
	workers: 1,
	plugins: null,
	https: false,
	isDebug: true,
	clusterPort: 39257,
	port: 7001,
})
let redis = app.redis
let saveIpConnect = getRedis(app.config.redis.client) // redis 实例
async function start() {
	redis = getRedis(app.config.redis.client)
	let v = await redis.subscribe("ip", () => {
	})
	app.logger.info("订阅事件%s", JSON.stringify(v))
	redis.on("message", function (channel, message) {
		if (channel == "ip") {
			let val = JSON.parse(message)
			queue.push({
				action: getIp, ip: val.ip
			})
		}
	})
}
//并发队列
let queue = require("async").queue(async (obj) => {
	await obj.action(obj.ip)
	await later(800)
}, 1)

function getRedis(client) {
	let ioredis = new Ioredis({
		port: client.port,
		host: client.host,
		password: client.password
	})
	return ioredis
}
start()

/**
	 * @returns {Promise<{country:string,city:string,region:string}>}
	 */
async function getIp(ip) {

	let ipInt = helper.ipV4toInt(ip)
	let data = await saveIpConnect.get("ip." + ipInt)
	if (data) {
		console.log(data)
		app.logger.info("已有缓存")
		return
	}
	process.stdout.write(ip)
	let addressInDb = await app.model.Address.findOne({where: ipInt})
	if (addressInDb) {
		app.logger.info("数据库已有缓存")
		let p2 = await saveIpConnect.set("ip." + ipInt, JSON.stringify({
			country: addressInDb.country,
			province: addressInDb.region,
			city: addressInDb.city,
		}), "EX", 3600 * 24 * 3) //数据库之中的

		return
	}

	app.logger.info("查询:" + ip)
	/* 	 */
	queryIp(ip).then(async (data) => {
		if (!Array.isArray(data)) {
			return
		}
		let p = app.model.Address.upsert({
			ip: ipInt,
			country: data[0],
			region: data[1],
			city: data[2],
		})
		let p2 = saveIpConnect.set("ip." + ipInt, JSON.stringify({
			country: data[0],
			province: data[1],
			city: data[2],
		}), "EX", 3600 * 24 * 3)
		await Promise.all([p, p2])
	}).catch((e) => {
		app.logger.warn("队列读取ip错误")
		// console.trace(e)
	})
}

function later(time, msg) {
	msg && console.log("延时" + time + "," + msg)
	if (time <= 0) {
		return Promise.resolve(time)
	}
	return new Promise(function (resolve, reject) {
		setTimeout(function () {
			resolve(time)
		}, time)
	})
}


process.on("uncaughtException", function (err) {
	app.logger.error(err)
})